package com.codingfuture.glacierhardware.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codingfuture.glaciercommon.entity.Meter;
import com.codingfuture.glaciercommon.util.PageDate;
import com.codingfuture.glaciercommon.util.PageParam;
import com.codingfuture.glaciercommon.util.Result;
import com.codingfuture.glacierhardware.dto.MeterAddDTO;
import com.codingfuture.glacierhardware.dto.MeterUpdateDTO;
import com.codingfuture.glacierhardware.service.MeterService;
import com.codingfuture.glacierhardware.vo.CompanyVO;
import com.codingfuture.glacierhardware.vo.HostVO;
import com.codingfuture.glacierhardware.vo.WareHouseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.http.HttpHeaders;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import static com.codingfuture.glaciercommon.constant.ResultConstant.*;


/**
 * @Author: Sun
 * @DateTime: 2025/3/31 16:16
 * @Description:
 **/
@Slf4j
@Api(tags = "仪表接口")
@RestController
@RequestMapping("/meter")
@RefreshScope
public class MeterController {
    @Autowired
    private MeterService meterService;

    /**
     * 仪表分页
     * ok
     *
     * @param companyName
     * @param pageParam
     * @return
     */
    @GetMapping("/findByPage")
    @ApiOperation("仪表分页")
    public Result<PageDate<List<Meter>>> findByPage(String companyName, PageParam pageParam) {
        Page<Meter> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        meterService.findByPage(companyName, page);
        PageDate<List<Meter>> pageDate = new PageDate<>();
        pageDate.setRows(page.getRecords());
        pageDate.setTotal(page.getTotal());
        return Result.OK(pageDate);
    }

    /**
     * 仪表添加
     * ok
     *
     * @param meterAddDTO
     * @return
     */
    @PostMapping("add")
    @ApiOperation("添加仪表")
    public Result<Void> addInfo(@RequestBody MeterAddDTO meterAddDTO) {
        return meterService.addInfo(meterAddDTO) ?
                Result.success(ADD_YES_MSG)
                : Result.err(ADD_NO_MSG);
    }

    /**
     * 修改仪表
     *
     * @param meterUpdateDTO
     * @return
     */
    @PostMapping("update")
    @ApiOperation("修改仪表")
    public Result<Void> updateInfo(@RequestBody MeterUpdateDTO meterUpdateDTO) {
        return meterService.updateInfo(meterUpdateDTO)
                ? Result.success(UPDA_YES_MSG)
                : Result.err(UPDA_NO_MSG);
    }

    /**
     * 删除仪表
     *
     * @param id
     * @return
     */

    @GetMapping("delete")
    @ApiOperation("删除仪表")
    public Result<Void> delById(@RequestParam Long id) {
        return meterService.delById(id) ? Result.success(DEL_YES_MSG) : Result.success(DEL_NO_MSG);
    }

    /**
     * 查询公司列表
     * ok
     *
     * @return
     */
    @GetMapping("getCompany")
    public Result<List<CompanyVO>> getCompany() {
        List<CompanyVO> companyVOS = meterService.getCompany();
        return Result.successes(companyVOS);
    }

    /**
     * 通过公司ID查询库房列表
     * ok
     *
     * @param id
     * @return
     */
    @GetMapping("getWareHouse")
    public Result<List<WareHouseVO>> getWareHouse(Long id) {
        List<WareHouseVO> wareHouseVOS = meterService.getWareHouse(id);
        return Result.successes(wareHouseVOS);
    }

    @GetMapping("findById")
    public Result<Meter> findById(@RequestParam Long id) {
        Meter meter = meterService.findById(id);
        return Result.successes(meter);
    }

    /**
     * 通过库房ID查询主机列表
     * ok
     *
     * @param id
     * @return
     */
    @GetMapping("getHost")
    public Result<List<HostVO>> getHost(@RequestParam Long id) {
        List<HostVO> hostListVOs = meterService.getHost(id);
        return Result.successes(hostListVOs);
    }

    /**
     * 打印excel表格接口，需要传文件流
     *
     * @return
     */
    @GetMapping(value = "getMeterExcel", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> getMeterExcel() throws IOException {
        List<Meter> meterList = meterService.getMeterExcel();

        // 创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("仪表数据");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("仪表ID");
        headerRow.createCell(1).setCellValue("仪表编号");
        headerRow.createCell(2).setCellValue("仪表名称");
        headerRow.createCell(11).setCellValue("最小温度");
        headerRow.createCell(12).setCellValue("最大温度");
        headerRow.createCell(13).setCellValue("最小湿度");
        headerRow.createCell(14).setCellValue("最大湿度");
        headerRow.createCell(15).setCellValue("采集间隔");
        headerRow.createCell(16).setCellValue("TOKEN");
        headerRow.createCell(17).setCellValue("设备类型");
        headerRow.createCell(18).setCellValue("状态");
        headerRow.createCell(19).setCellValue("创建时间");
        headerRow.createCell(20).setCellValue("更新时间");
        headerRow.createCell(3).setCellValue("主机ID");
        headerRow.createCell(4).setCellValue("主机编号");
        headerRow.createCell(5).setCellValue("主机名称");
        headerRow.createCell(6).setCellValue("仓库ID");
        headerRow.createCell(7).setCellValue("仓库编号");
        headerRow.createCell(8).setCellValue("仓库名称");
        headerRow.createCell(9).setCellValue("公司ID");
        headerRow.createCell(10).setCellValue("公司名称");
        headerRow.createCell(21).setCellValue("备注信息");

        // 填充数据
        int rowNum = 1;
        for (Meter meter : meterList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(meter.getId());
            row.createCell(1).setCellValue(meter.getSn());
            row.createCell(2).setCellValue(meter.getName());
            row.createCell(3).setCellValue(meter.getMinTem());
            row.createCell(4).setCellValue(meter.getMaxTem());
            row.createCell(5).setCellValue(meter.getMinTem());
            row.createCell(6).setCellValue(meter.getMaxTem());
            row.createCell(7).setCellValue(meter.getCollectInterval());
            row.createCell(8).setCellValue(meter.getToken());
            row.createCell(9).setCellValue(meter.getType());
            row.createCell(10).setCellValue(meter.getState());
            row.createCell(11).setCellValue(meter.getCreateTime());
            row.createCell(12).setCellValue(meter.getUpdateTime());
            row.createCell(13).setCellValue(meter.getHostId());
            row.createCell(14).setCellValue(meter.getHostSn());
            row.createCell(15).setCellValue(meter.getHostName());
            row.createCell(16).setCellValue(meter.getWarehouseId());
            row.createCell(17).setCellValue(meter.getWarehouseSn());
            row.createCell(18).setCellValue(meter.getWarehouseName());
            row.createCell(19).setCellValue(meter.getCompanyId());
            row.createCell(20).setCellValue(meter.getCompanyName());
            row.createCell(21).setCellValue(meter.getRemark());
        }

        // 将工作簿转换为字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "meter_data.xlsx");

        return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
    }
}
